package indi.kider.server.woniubus.service;

import indi.kider.common.constant.EmployeeRoleCons;
import indi.kider.common.constant.StatusCons;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.apartment.Community;
import indi.kider.common.model.apartment.Houses;
import indi.kider.common.model.apartment.HousesMsg;
import indi.kider.common.model.employee.Employee;
import indi.kider.common.model.employee.TenantQuery;
import indi.kider.common.model.woniubus.HouseVo;
import indi.kider.server.apartment.mapper.CommunityMapper;
import indi.kider.server.apartment.mapper.HouseMapper;
import indi.kider.server.apartment.mapper.HousesMapper;
import indi.kider.server.apartment.model.CommunityTitle;
import indi.kider.server.apartment.model.HouseRent;
import indi.kider.server.apartment.model.HousesCommunityQuery;
import indi.kider.server.woniubus.pageModel.CommunityPageQuery;
import indi.kider.server.woniubus.util.BuildModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.vankid.common.model.base.CoreException;
import pers.vankid.common.utils.page.PageRequest;
import pers.vankid.common.utils.page.PageResponse;
import pers.vankid.common.utils.page.PageUtil;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
@Service
public class HouseServiceImpl implements HouseService {

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private HousesMapper housesMapper;

    @Autowired
    private HouseMapper houseMapper;

//    @Autowired
//    private RentOutlineMapper rentOutlineMapper;

    /**
     * 获取房源列表
     * @param request
     * @return
     */
    public PageResponse<CommunityTitle> houseList(PageRequest<HousesCommunityQuery> request) {
        HousesCommunityQuery query = request.getQuery();
        Community community = communityMapper.selectByPrimaryKey(query.getCommunityId());
        PageUtil.start(request);
        List<Houses> voList = housesMapper.getHouseRentList(query);
        PageResponse<Houses> pageResponse = PageUtil.getPageResponse(voList);
        List<HouseRent> houseRentList = new ArrayList<>();
        voList.stream().forEach(vo -> {
            HouseRent houseRent = BuildModel.buildHouseRentsByHouse(vo);
            houseRent.setCommunity(community.getCommunity());
            houseRentList.add(houseRent);
        });
        List<CommunityTitle> communityTitles = new ArrayList<>();
        CommunityTitle c = new CommunityTitle();
        c.setOpen(true);
        c.setRoomList(houseRentList);
        c.setCommunityId(query.getCommunityId());
        c.setCommunity(community.getCommunity());
        communityTitles.add(c);
        PageResponse<CommunityTitle> re = new PageResponse(communityTitles, pageResponse.getTotal(),pageResponse.getSize());
        return re;
    }

    /**
     * 获取公寓列表
     * @param request
     * @return
     */
    public PageResponse<Community> communityList(PageRequest<CommunityPageQuery> request) {
        CommunityPageQuery query = request.getQuery();
        Example example = new Example(Community.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIsNotNull("id");
        if(StringUtil.isNotEmpty(query.getCommunity())){
            criteria.andLike("community","%"+query.getCommunity()+"%");
        }
        if(checkInteger(query.getType())){
            criteria.andEqualTo("type", query.getType());
        }
        if(checkLong(query.getEnterpriseId())){
            criteria.andEqualTo("enterpriseId", query.getEnterpriseId());
        }
        PageUtil.start(request);
        List<Community> list= communityMapper.selectByExample(example);
        PageResponse<Community> pageResponse = PageUtil.getPageResponse(list);
        return pageResponse;
    }

    private boolean  checkInteger(Integer i){
        if(i!=null && i>0){
            return true;
        }
        return false;
    }

    private boolean  checkLong(Long i){
        if(i!=null && i>0){
            return true;
        }
        return false;
    }

    @Override
    public Map<String, Object> getHouseUserCntMap(Long houseId) throws Exception{
        //inSumCnt:3,inManCnt:1,inFemanCnt:2
        if(houseId==null){
            throw new Exception("缺少房间主键");
        }
        Map<String, Object> map =  houseMapper.getHouseUserCntMap(houseId);
        Houses houses = housesMapper.selectByPrimaryKey(houseId);
        if(map != null){
            BigDecimal a  = (BigDecimal)map.get("inSumCnt");
            BigDecimal b  = (BigDecimal)map.get("inManCnt");
            BigDecimal c  = (BigDecimal)map.get("inFemanCnt");
            houses.setInSumCnt(a.intValue());
            houses.setInManCnt(b.intValue());
            houses.setInFemanCnt(c.intValue());
            // 出租类型 1 独租公寓 2群租公寓
            if(houses.getComType()== 2 && houses.getInManCnt()>0 && houses.getInFemanCnt()>0){
                throw  new CoreException("不能男女混居!");
            }
        }else{
            houses.setInSumCnt(0);
            houses.setInManCnt(0);
            houses.setInFemanCnt(0);
        }
        housesMapper.updateByPrimaryKeySelective(houses);
        return map;
    }

    public List<Community> queryCommunityTenantList(Employee employee){
        List<Community> communitys = new ArrayList<>();
        Community community = new Community();
        if(employee.getRoles().equals(EmployeeRoleCons.BUILDING)){//楼栋管理员
            communitys = houseMapper.getCommunityByLouId(employee.getId());
        }else if(employee.getRoles().equals(EmployeeRoleCons.FIVE)){//合作方
            communitys = houseMapper.getCommunityByPartId(employee.getId());
        }else{
            if(!employee.getRoles().equals(EmployeeRoleCons.ADMIN)) {
                community.setEnterpriseId(employee.getEnterpriseId());
            }
            communitys = communityMapper.select(community);
            communitys.stream().forEach(community1 -> {
                        TenantQuery tenantQuery=new TenantQuery();
                        tenantQuery.setCommunityId(community1.getId());
                        tenantQuery.setState(StatusCons.VALID);
                        community1.setTenantSizeNow(communityMapper.getTenantSizeByCommunity(tenantQuery));
                    }
            );
        }
        return communitys;
    }


    public List<Community> queryCommunityList(Employee employee){
        List<Community> communitys = new ArrayList<>();
        if(employee.getRoles().equals(EmployeeRoleCons.FIVE)){//合作方
            communitys = houseMapper.getCommunityByPartId(employee.getId());
        }else if(employee.getRoles().equals(EmployeeRoleCons.BUILDING)){//楼栋管理员
            communitys = houseMapper.getCommunityByLouId(employee.getId());
        }else{
            Community community = new Community();
            if(!employee.getRoles().equals(EmployeeRoleCons.ADMIN)) {
                community.setEnterpriseId(employee.getEnterpriseId());
            }
            communitys = communityMapper.select(community);
            communitys.stream().forEach(community1 -> {
                        community1.setSize(housesMapper.selectCommunityHousesSize(community1.getId()));
                    }
            );
            return communitys;
        }
        return communitys;
    }


    public  List<Map> queryHouseList(Long communityId)throws Exception {
        return houseMapper.queryHouseList(communityId);
    }

    /**
     * 根据房屋ID查询房屋信息。
     * @param houseId
     * @return
     */
    @Override
    public HouseVo getHouseById(Long houseId) {
        return houseMapper.getHouseById(houseId);
    }
}
